package com.zh.myutils;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;
import java.util.logging.Logger;

/**
 * 文件操作的工具类
 */
public class FileOperationUtils {

    /**
     * 文件下载
     * @param filepath 源文件路径
     * @param fileName 文件名称（可选）
     * @param response response参数
     * @return boolean类型
     * @throws IOException IO异常
     */
    public static boolean download(String filepath,String fileName,HttpServletResponse response) throws IOException {
        // 创建文件对象
        File file = new File(filepath);
        // 若是没有指定文件名，则随机生成文件名
        if(fileName == null){
            int index = filepath.lastIndexOf(".");
            if(index > 0){
                fileName = UUID.randomUUID()+filepath.substring(index);
            }else{
                Logger.getGlobal().warning("文件路径没有后缀名");
            }
        }
        // 设置响应头
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        // 字节流输出
        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
        OutputStream os = null;
        try {
            os = response.getOutputStream();
            bis = new BufferedInputStream(new FileInputStream(file));
            int i = bis.read(buff);
            while (i != -1) {
                os.write(buff, 0, buff.length);
                os.flush();
                i = bis.read(buff);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return false;
    }

}
